package com.learning.spring.cloud.alibaba.hystrix.user.web.command;


import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPoolKey;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: HystrixCustomCommand
 * Description: 自定义 HystrixCommand
 * Date: 2021/8/23 11:15 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Slf4j
public class HystrixCustomCommand extends HystrixCommand<List> {

    RestTemplate restTemplate;
    String serviceId;

    public HystrixCustomCommand(RestTemplate restTemplate, String serviceId) {
        super(
                Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("Learning-Hystrix-Command"))
                        .andCommandKey(HystrixCommandKey.Factory.asKey("UserController"))
                        .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("LearningHystrixCommandThreadPool"))
                        .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                                // 超时事件
                                .withExecutionTimeoutInMilliseconds(100)
                                // 熔断的时长
                                .withCircuitBreakerSleepWindowInMilliseconds(5000))
                        .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
                                // 线程池核心线程数
                                .withCoreSize(1)
                                // 线程池任务队列
                                .withMaxQueueSize(2))

        );
        this.restTemplate = restTemplate;
        this.serviceId = serviceId;
    }

    /**
     * 核心执行方法
     *
     * @return
     * @throws Exception
     */
    @Override
    protected List run() throws Exception {
        log.info("线程名称：{}", Thread.currentThread().getName());
        return this.restTemplate.getForObject(serviceId, List.class);
    }

    /**
     * 回退方法
     *
     * @return
     */
    @Override
    protected List getFallback() {
        List<String> list = new ArrayList<>();
        list.add("降级，返回回退的商品");
        return list;
    }
}
